﻿using System;
using Best.SmartCms.Core.Utility;
using Best.SmartCms.Dto.Response;
using Best.SmartCms.Service.BizException;
using Best.SmartCms.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Best.SmartCms.API.Filters
{
    /// <summary>
    /// 日志拦截机制
    /// </summary>
    public class ExceptionFilter : IExceptionFilter
    {
      /// <summary>
      /// 
      /// </summary>
      /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            ApiResponse res;
            if (context.Exception is BizExceptionBase bizException)
            {
                res = HandleBizException(bizException);
            }
            else
            {
                NLogManager.LogError(context.Exception.Message + Environment.NewLine + context.Exception.StackTrace);
                res = HandleGeneralException(context.Exception);
            }

            context.Result = new ObjectResult(res);
            context.ExceptionHandled = true;
        }

        private static ApiResponse HandleBizException(BizExceptionBase bizException)
        {
            return new ApiResponse
            {
                Code = bizException.ExceptionCode,
                Message = bizException.Message
            };
        }

        private static ApiResponse HandleGeneralException(Exception exception)
        {
            return new ApiResponse
            {
                Code = ResponseCode.SystemError,
                Message = exception.Message
            };
        }
    }
}
